package cn.iocoder.yudao.module.datasource.config;

import cn.iocoder.yudao.module.datasource.core.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置类
 * 只有在启用自定义数据源时才生效
 *
 * @author 芋道源码
 */
@Configuration
@ConditionalOnProperty(prefix = "yudao.datasource", name = "enabled", havingValue = "true", matchIfMissing = false)
@Slf4j
public class DataSourceConfiguration {

    /**
     * 创建动态路由数据源
     * 注意：只有显式启用时才会创建
     */
    @Bean
    @Primary
    public DynamicRoutingDataSource dynamicDataSource() {
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        
        // 初始化时创建空的数据源映射
        Map<Object, Object> targetDataSources = new HashMap<>();
        
        // 可以在这里添加默认数据源，但为了不影响现有系统，暂时留空
        dynamicRoutingDataSource.setTargetDataSources(targetDataSources);
        
        log.info("自定义动态数据源已初始化");
        
        return dynamicRoutingDataSource;
    }
}